import 'dart:async';

import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim/routes/app_navigator.dart';
import 'package:openim_common/openim_common.dart';

import '../../../core/controller/im_controller.dart';
import '../../home/home_logic.dart';

class FriendRequestsLogic extends GetxController {
  final imLogic = Get.find<IMController>();
  final homeLogic = Get.find<HomeLogic>();
  final applicationList = <FriendApplicationInfo>[].obs;
  late StreamSubscription faSub;

  @override
  void onInit() {
    faSub = imLogic.friendApplicationChangedSubject.listen((value) {
      _getFriendRequestsList();
    });
    super.onInit();
  }

  @override
  void onReady() {
    _getFriendRequestsList();
    super.onReady();
  }

  @override
  void onClose() {
    faSub.cancel();
    homeLogic.getUnhandledFriendApplicationCount();
    super.onClose();
  }

  void _getFriendRequestsList() async {
    final list = await Future.wait([
      OpenIM.iMManager.friendshipManager.getFriendApplicationListAsRecipient(),
      OpenIM.iMManager.friendshipManager.getFriendApplicationListAsApplicant(),
    ]);

    final allList = <FriendApplicationInfo>[];
    allList
      ..addAll(list[0])
      ..addAll(list[1]);

    allList.sort((a, b) {
      if (a.createTime! > b.createTime!) {
        return -1;
      } else if (a.createTime! < b.createTime!) {
        return 1;
      }
      return 0;
    });

    var haveReadList = DataSp.getHaveReadUnHandleFriendApplication();
    haveReadList ??= <String>[];
    for (var e in list[0]) {
      var id = IMUtils.buildFriendApplicationID(e);
      if (!haveReadList.contains(id)) {
        haveReadList.add(id);
      }
    }
    DataSp.putHaveReadUnHandleFriendApplication(haveReadList);

    for (final app in allList) {
      try {
        if (app.fromUserID != null && app.fromUserID!.isNotEmpty) {
          final from = await Apis.getUserProfileByOpenIMID(app.fromUserID!);
          if (from != null) {
            app.fromNickname = from.nickname ?? app.fromNickname;
            app.fromFaceURL = from.faceURL ?? app.fromFaceURL;
          }
        }
        if (app.toUserID != null && app.toUserID!.isNotEmpty) {
          final to = await Apis.getUserProfileByOpenIMID(app.toUserID!);
          if (to != null) {
            app.toNickname = to.nickname ?? app.toNickname;
            app.toFaceURL = to.faceURL ?? app.toFaceURL;
          }
        }
      } catch (_) {}
    }

    applicationList.assignAll(allList);
  }

  bool isISendRequest(FriendApplicationInfo info) => info.fromUserID == OpenIM.iMManager.userID;

  void acceptFriendApplication(FriendApplicationInfo info) => AppNavigator.startProcessFriendRequests(
        applicationInfo: info,
      );

  void refuseFriendApplication(FriendApplicationInfo info) async {}
  // 查看朋友详情
  void viewFriendInfo(FriendApplicationInfo info) async {
    final isISendRequest = info.fromUserID == OpenIM.iMManager.userID;
    final openimID = isISendRequest ? info.toUserID : info.fromUserID;
    final profile = await LoadingView.singleton.wrap(
      asyncFunction: () => Apis.getUserProfileByOpenIMID(openimID!),
    );
      final nickname = isISendRequest ? info.toNickname : info.fromNickname;
      final faceURL = isISendRequest ? info.toFaceURL : info.fromFaceURL;
      AppNavigator.startUserProfilePane(
        userID: openimID!,
        nickname: nickname,
        faceURL: faceURL,
      );
  }
}
